package com.lkm.market2_0.m_imple.steelyarddata;

import com.google.gson.Gson;
import com.lkm.frame.task2.ITaskExecutor;
import com.lkm.frame.task2.TaskAdapter;
import com.lkm.frame.task2.TaskManager;
import com.lkm.javatool.IOHelp;
import com.lkm.javatool.StringHelp;
import com.lkm.market2_0.ExpandConfig;
import com.lkm.market2_0.entity.SteelyardInfo;
import com.lkm.market2_0.m.steelyarddata.OrderEntity;
import com.lkm.market2_0.m.steelyarddata.SteelyardDataModule;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



class Cache2SaveOrderTask extends TaskAdapter<Object[], Void, Boolean> {

    private DataManager dataManager;

    private SteelyardDataModule dataModule ;
    public Cache2SaveOrderTask(DataManager dataManager, SteelyardDataModule dataModule, ITaskExecutor<Object[], Void, Boolean> taskExecutor, TaskManager mTaskManager) {
//            SaveDataTask.class.getName()
        super(taskExecutor, "app_saveOrder_TaskId", mTaskManager);
        this.dataManager = dataManager;
        this.dataModule = dataModule;
    }

    private List<OrderEntity> orderEntities = new ArrayList<>();
    public void add(OrderEntity orderEntity){
        synchronized (Cache2SaveOrderTask.this){
            orderEntities.add(orderEntity);
            
            if(orderEntity.isFullOrder())
            if(ExpandConfig.instance.isUI()){
                saveOrdersToFile(new Runnable() {
                    @Override
                    public void run() {
                        dataManager.updataData();
                    }
                });
            }
        }

    }

    @Override
    public void doExecuting(Object[] param) {
        super.doExecuting(param);
        postSave();
    }
    
    private void postSave(){
        mTaskExecutor.post(new Runnable() {
            @Override
            public void run() {
                saveOrdersToFile(new Runnable() {
                    @Override
                    public void run() {
                        postSave();
                    }
                });

            }
        },3000);
    }

    
    private void saveOrdersToFile(Runnable endrun) {
        mTaskExecutor.executor(new Runnable() {
            @Override
            public void run() {
                try{
                List<OrderEntity> tempOrderEntities = null;
                synchronized (Cache2SaveOrderTask.this) {
                    tempOrderEntities = orderEntities;
                    orderEntities = new ArrayList<>();
                }

                StringBuilder stringBuilder = new StringBuilder();
                int size = tempOrderEntities.size();
                for (int i = 0; i < size; i++) {
                    OrderEntity orderEntity = tempOrderEntities.get(i);
                    stringBuilder.append(new Gson().toJson(orderEntity));
                    stringBuilder.append("\n");
                }

                if (size > 0) {
                    boolean isSuccess = false;
                    try {
                        isSuccess = SaveString(com.lkm.market2_0.m_imple.steelyarddata.FileManager.getCanUpdateCahceOrdersFile(), stringBuilder.toString(), "utf-8", false);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (!isSuccess) {
                        synchronized (Cache2SaveOrderTask.this) {
                            
                            tempOrderEntities.addAll(orderEntities);
                            orderEntities = tempOrderEntities;
                        }
                    } else {
                        saveOrdernumToOrg(tempOrderEntities);
                    }
                }}finally {
                    if(endrun!=null)endrun.run();
                }

            }
        });
    }

    
    private void saveOrdernumToOrg(List<OrderEntity> tempOrderEntities) {
        if (ExpandConfig.instance.isTest()) {
            return;
        }
        int size = tempOrderEntities.size();

        

        Map<String, String> orgOrderNumMap = new HashMap<>();
        for (int i = 0; i < size; i++) {
            OrderEntity orderEntity = tempOrderEntities.get(i);

            if (orderEntity.isFullOrder() && !StringHelp.isEmpty(orderEntity.orderNum)) {
                SteelyardInfo steelyardInfo =  dataModule.getSteelyardInfo(orderEntity.steelyardMac);

                
                if (steelyardInfo != null && steelyardInfo.codetype == SteelyardInfo.codetype_0) {
                    
                    //Config.instance.saveValue("ordernum_" + orderEntity.orderNum.substring(0, Config.nodeCodeLength), orderEntity.orderNum);
                    orgOrderNumMap.put(orderEntity.orderNum.substring(0, ExpandConfig.nodeCodeLength), orderEntity.orderNum);
                }
            }
        }

        for (Map.Entry<String, String> orderNum : orgOrderNumMap.entrySet()) {
            ExpandConfig.instance.saveValue("ordernum_" + orderNum.getKey(), orderNum.getValue());
        }
    }


    

    private synchronized boolean SaveString(String filename, String content,  String charset, boolean isClearOld) {
        if (content == null || content.isEmpty()) {
            return false;
        }

        boolean is = false;

        boolean isNewFile = false;
          BufferedWriter bw = null;
          FileOutputStream fos = null;
        try {
            if (bw == null) {
                String directory = ExpandConfig.instance.getOrderTempFileDir();
//                String filename = "cahceOrders-update"+System.currentTimeMillis()+".json";

                File file = new File(directory);

                if (!file.exists() || !file.isDirectory()) {
                    file.delete();
                    file.mkdirs();
                    isNewFile = true;
                } else {
                    
                    isNewFile = false;
                }
                String path = file.getPath() + File.separator + filename;
                File f = new File(path);
                if (isClearOld) {
                    f.delete();
                    if (!f.createNewFile()) {
                        return false;
                    }
                }
                fos = new FileOutputStream(f, true);
                bw = new BufferedWriter(new OutputStreamWriter(fos, charset));
            }







            bw.append(content);


            bw.flush();
            is = true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOHelp.close(bw);
            IOHelp.close(fos);
        }
        return is;
    }



}
